import { NextRequest, NextResponse } from "next/server";
import { auth } from "@clerk/nextjs";
import { prisma } from "@/lib/prisma";

// 获取单个知识库详情
export async function GET(
  req: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const { userId } = auth();

    // 检查用户认证
    if (!userId) {
      return NextResponse.json(
        { success: false, error: "未授权" },
        { status: 401 }
      );
    }

    const { id } = params;

    // 获取知识库及其文档
    const knowledgeBase = await prisma.knowledgeBase.findUnique({
      where: { id },
      include: {
        documents: {
          orderBy: { createdAt: "desc" },
        },
      },
    });

    if (!knowledgeBase) {
      return NextResponse.json(
        { success: false, error: "知识库不存在" },
        { status: 404 }
      );
    }

    // 检查是否是当前用户的知识库
    const user = await prisma.user.findUnique({
      where: { clerkId: userId },
    });

    if (!user || knowledgeBase.userId !== user.id) {
      return NextResponse.json(
        { success: false, error: "无权访问此知识库" },
        { status: 403 }
      );
    }

    return NextResponse.json({
      success: true,
      data: knowledgeBase,
    });
  } catch (error) {
    console.error("获取知识库详情失败:", error);
    return NextResponse.json(
      { success: false, error: "获取知识库详情失败" },
      { status: 500 }
    );
  }
}

// 更新知识库
export async function PATCH(
  req: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const { userId } = auth();

    // 检查用户认证
    if (!userId) {
      return NextResponse.json(
        { success: false, error: "未授权" },
        { status: 401 }
      );
    }

    const { id } = params;
    const body = await req.json();
    const { name, description } = body;

    // 验证请求数据
    if (!name || typeof name !== "string") {
      return NextResponse.json(
        { success: false, error: "知识库名称是必填项" },
        { status: 400 }
      );
    }

    // 检查知识库是否存在
    const knowledgeBase = await prisma.knowledgeBase.findUnique({
      where: { id },
    });

    if (!knowledgeBase) {
      return NextResponse.json(
        { success: false, error: "知识库不存在" },
        { status: 404 }
      );
    }

    // 检查是否是当前用户的知识库
    const user = await prisma.user.findUnique({
      where: { clerkId: userId },
    });

    if (!user || knowledgeBase.userId !== user.id) {
      return NextResponse.json(
        { success: false, error: "无权修改此知识库" },
        { status: 403 }
      );
    }

    // 更新知识库
    const updatedKnowledgeBase = await prisma.knowledgeBase.update({
      where: { id },
      data: {
        name,
        description,
      },
    });

    return NextResponse.json({
      success: true,
      data: updatedKnowledgeBase,
    });
  } catch (error) {
    console.error("更新知识库失败:", error);
    return NextResponse.json(
      { success: false, error: "更新知识库失败" },
      { status: 500 }
    );
  }
}

// 删除知识库
export async function DELETE(
  req: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const { userId } = auth();

    // 检查用户认证
    if (!userId) {
      return NextResponse.json(
        { success: false, error: "未授权" },
        { status: 401 }
      );
    }

    const { id } = params;

    // 检查知识库是否存在
    const knowledgeBase = await prisma.knowledgeBase.findUnique({
      where: { id },
    });

    if (!knowledgeBase) {
      return NextResponse.json(
        { success: false, error: "知识库不存在" },
        { status: 404 }
      );
    }

    // 检查是否是当前用户的知识库
    const user = await prisma.user.findUnique({
      where: { clerkId: userId },
    });

    if (!user || knowledgeBase.userId !== user.id) {
      return NextResponse.json(
        { success: false, error: "无权删除此知识库" },
        { status: 403 }
      );
    }

    // 删除知识库（关联的文档和向量将通过级联删除）
    await prisma.knowledgeBase.delete({
      where: { id },
    });

    return NextResponse.json({
      success: true,
      data: { message: "知识库已成功删除" },
    });
  } catch (error) {
    console.error("删除知识库失败:", error);
    return NextResponse.json(
      { success: false, error: "删除知识库失败" },
      { status: 500 }
    );
  }
} 